package cn.hhz._05weibo.controller;

import cn.hhz._05weibo.common.response.JsonResult;
import cn.hhz._05weibo.common.response.StatusCode;
import cn.hhz._05weibo.mapper.UserMapper;
import cn.hhz._05weibo.pojo.dto.UserLoginDTO;
import cn.hhz._05weibo.pojo.dto.UserRegDTO;
import cn.hhz._05weibo.pojo.entity.User;
import cn.hhz._05weibo.pojo.vo.UserV0;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j//日志注解
@RestController
@RequestMapping("v1/users/")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @ApiOperation("注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO) {
        log.debug("userRegDTO = " + userRegDTO);
        UserV0 userV0 = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userV0 != null) {
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        System.out.println("userLoginDTO = " + userLoginDTO);
        UserV0 userV0 = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userV0 == null) {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userLoginDTO.getPassword().equals(userV0.getPassword())) {
            session.setAttribute("user", userV0);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    @ApiOperation("获取当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        UserV0 userV0 = (UserV0) session.getAttribute("user");
        return JsonResult.ok(userV0);
    }

    @ApiOperation("退出登录功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }
}
